/* 
标签控制器
场景：创建标签
*/
const Tag = require('../model/tag')
const HttpException = require('../exception/http.exception.js');

//创建标签
const createTagController = async (req, res, next) => {
    try {
        const tag = req.body.tag
        //标签校验
        if (!tag) {
            throw new HttpException(401, 'tag 标签必须传递', 'tag not found')
        }
        //标签存储
        const result = await Tag.create({ name: tag })
        // console.log(result);

        return res.status(200)
            .json({
                status: 1,
                message: "OK",
                data: result
            })
    } catch (error) {
        next(error)
    }

}

//获取标签列表
const getTagsController = async (req, res, next) => {
    try {
        const tagsAll = await Tag.findAll()
        // console.log(tagsAll);

        const tags = []
        for (const tag of tagsAll) {
            console.log(tag.name);
            tags.push(tag.name)
        }
        return res.status(200)
            .json({
                status: 1,
                message: '获取标签成功',
                data: tags

            })
    } catch (error) {

    }
}
//删除标签列表
const deleteTagsController = async (req, res, next) => {
    try {
        const tag = req.params.tag
        const destroyResult = await Tag.destroy({
            where: {
                name: tag
            }
        })
        // console.log(destroyResult);
        const tagsAll = await Tag.findAll()
        const tags = []
        if (tagsAll.length > 0) {
            for (const tag of tagsAll) {
                console.log(tag.name);
                tags.push(tag.name)
            }
        }

        return res.status(200)
            .json({
                status: 1,
                message: '删除标签成功',
                data: tags

            })
    } catch (error) {
        next(error)
    }
}
module.exports = {
    createTagController,
    getTagsController,
    deleteTagsController
}